package com.colorful.hrm.config;

import com.colorful.hrm.handler.DefaultAccessDeniedHandler;
import com.colorful.hrm.handler.MyAuthenticationFailureHandler;
import com.colorful.hrm.handler.MyAuthenticationSuccessHandler;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity //开启web安全配置
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    //提供用户信息，这里没有从数据库查询用户信息，在内存中模拟
//    @Bean
//    public UserDetailsService userDetailsService(){
//        InMemoryUserDetailsManager inMemoryUserDetailsManager =
//                new InMemoryUserDetailsManager();
//        inMemoryUserDetailsManager.createUser(User.withUsername("zs").password("123").authorities("admin").build());
//        return inMemoryUserDetailsManager;
//    }

    //密码编码器：不加密
    @Bean
    public PasswordEncoder passwordEncoder(){
        //return NoOpPasswordEncoder.getInstance();
        return new BCryptPasswordEncoder();
    }

    @Autowired
    private MyAuthenticationSuccessHandler successHandler;
    @Autowired
    private MyAuthenticationFailureHandler failureHandler;
    @Autowired
    private DefaultAccessDeniedHandler accessDeniedHandler;
    //授权规则配置
    @Override //http安全配置
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()                               //授权配置
                .antMatchers("/login").permitAll()  //登录路径放行
                .antMatchers("/login.html").permitAll()//登录页面放行
                //============权限控制方案1：代码控制== 1 restfull支持不好，2 查询所有权限表所有的数据都要添加过来==========//
//                .antMatchers("/employee/list").hasAuthority("employee:list")
                //============权限控制============//
                .anyRequest().authenticated()                   //其他路径都要认证之后才能访问
                .and().formLogin()                              //允许表单登录
//                .successForwardUrl("/loginSuccess")             // 设置登陆成功页
                .successHandler(successHandler )                 //登录成功json数据返回
                .failureHandler(failureHandler)
                .loginPage("/login.html")            //没有登录跳转的页面
                .loginProcessingUrl("/login")         //登录处理地址

                .and().logout().permitAll()                    //登出路径放行 /logout
                .and().csrf().disable();                        //关闭跨域伪造检查


        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);

        //记住我
        http.rememberMe()
                .tokenRepository(repository)
                .tokenValiditySeconds(3600)
                .userDetailsService(userDetailsService);
    }

    @Autowired
    private PersistentTokenRepository repository;
    @Autowired
    private UserDetailsService userDetailsService;

    //记住我功能实现配置如下：
    @Bean
    public PersistentTokenRepository repository(){
        JdbcTokenRepositoryImpl repository = new JdbcTokenRepositoryImpl();
        repository.setDataSource(dataSource()); //要访问数据库必须设置数据源
//        repository.setCreateTableOnStartup(true); //自己见persistent_logins
        return  repository;
    }

    @Bean
    @Primary//主数据源
    @ConfigurationProperties("spring.datasource1")
    public DataSource dataSource(){
        return DataSourceBuilder.create().build();
    }

}